package com.dtflys.easyel.runtime.eval;

import com.dtflys.easyel.ast.ASTIdentifier;
import com.dtflys.easyel.exception.EasyElEvalException;
import com.dtflys.easyel.runtime.EasyElRuntimeContext;
import com.dtflys.easyel.utils.MetaHelper;

import java.util.Map;

/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since v1.0.0
 */
public class IdentifierEvaluator {

    public Object evaluate(EasyElRuntimeContext context, ASTIdentifier identifier) {
        String idName = identifier.getName();
        Map<String, Object> env = context.getEnv();
        Object ret = env.get(idName);
        if (ret != null) {
            return MetaHelper.wrap(ret);
        }
        EasyElRuntimeContext parent = context.getParent();
        if (parent == null) {
            throw new EasyElEvalException(context, identifier,
                    "No such variable named '" + idName + "' is defined");
        }
        return evaluate(parent, identifier);
    }


}
